package com.ruoyi.system.service.impl;

import java.util.List;
import java.util.regex.Pattern;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.EmployeeMapper;
import com.ruoyi.system.domain.Employee;
import com.ruoyi.system.service.IEmployeeService;

/**
 * 培训人员管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-15
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService 
{
    @Autowired
    private EmployeeMapper employeeMapper;
    private static final Logger log = LoggerFactory.getLogger(EmployeeServiceImpl.class);
    /**
     * 查询培训人员管理
     * 
     * @param id 培训人员管理主键
     * @return 培训人员管理
     */
    @Override
    public Employee selectEmployeeById(Long id)
    {
        return employeeMapper.selectEmployeeById(id);
    }

    /**
     * 查询培训人员管理列表
     * 
     * @param employee 培训人员管理
     * @return 培训人员管理
     */
    @Override
    public List<Employee> selectEmployeeList(Employee employee)
    {
        return employeeMapper.selectEmployeeList(employee);
    }

    /**
     * 新增培训人员管理
     * 
     * @param employee 培训人员管理
     * @return 结果
     */
    @Override
    public int insertEmployee(Employee employee)
    {
        // 检查手机号是否已存在
        Employee existingEmployee = employeeMapper.selectEmployeeByPhone(employee.getPhone());
        if (existingEmployee != null) {
            throw new ServiceException("手机号 " + employee.getPhone() + " 已存在，请勿重复添加");
        }
        // 设置默认密码为123456
        if (StringUtils.isEmpty(employee.getPassword())) {
            employee.setPassword(SecurityUtils.encryptPassword("123456"));
        } else {
            employee.setPassword(SecurityUtils.encryptPassword(employee.getPassword()));
        }
        return employeeMapper.insertEmployee(employee);
    }
    /**
     * 修改培训人员管理
     * 
     * @param employee 培训人员管理
     * @return 结果
     */
    @Override
    public int updateEmployee(Employee employee)
    {
        // 检查手机号是否已存在（排除当前正在更新的员工）
        Employee existingEmployee = employeeMapper.selectEmployeeByPhone(employee.getPhone());
        if (existingEmployee != null && !existingEmployee.getId().equals(employee.getId())) {
            throw new ServiceException("手机号 " + employee.getPhone() + " 已存在，无法更新");
        }

        // 如果密码不为空，则进行加密处理
        if (StringUtils.isNotEmpty(employee.getPassword())) {
            employee.setPassword(SecurityUtils.encryptPassword(employee.getPassword()));
        } else {
            // 如果密码为空，则保持原密码不变
            Employee currentEmployee = employeeMapper.selectEmployeeById(employee.getId());
            if (currentEmployee != null) {
                employee.setPassword(currentEmployee.getPassword());
            }
        }
        return employeeMapper.updateEmployee(employee);
    }
    /**
     * 批量删除培训人员管理
     * 
     * @param ids 需要删除的培训人员管理主键
     * @return 结果
     */
    @Override
    public int deleteEmployeeByIds(Long[] ids)
    {
        return employeeMapper.deleteEmployeeByIds(ids);
    }

    /**
     * 删除培训人员管理信息
     * 
     * @param id 培训人员管理主键
     * @return 结果
     */
    @Override
    public int deleteEmployeeById(Long id)
    {
        return employeeMapper.deleteEmployeeById(id);
    }

    /**
     * 根据手机号查询员工信息
     *
     * @param phone 手机号
     * @return 员工信息
     */
    @Override
    public Employee selectEmployeeByPhone(String phone)
    {
        return employeeMapper.selectEmployeeByPhone(phone);
    }

    @Override
    public String importEmployee(List<Employee> employeeList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(employeeList) || employeeList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (Employee employee : employeeList) {
            try {
                // 验证数据
                if (!validateEmployee(employee)) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、员工姓名 " + employee.getEmpName() + " 数据格式不正确");
                    continue;
                }

                // 检查手机号是否已存在（排除当前正在更新的员工）
                Employee existingPhoneEmployee = employeeMapper.selectEmployeeByPhone(employee.getPhone());
                if (existingPhoneEmployee != null && !existingPhoneEmployee.getId().equals(employee.getId())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、员工姓名 " + employee.getEmpName() + " 手机号 " + employee.getPhone() + " 已存在");
                    continue;
                }

                // 设置默认密码为123456
                if (StringUtils.isEmpty(employee.getPassword())) {
                    employee.setPassword(SecurityUtils.encryptPassword("123456"));
                } else {
                    employee.setPassword(SecurityUtils.encryptPassword(employee.getPassword()));
                }

                // 如果ID存在，检查该ID的员工是否已存在
                Employee existingEmployee = null;
                if (employee.getId() != null) {
                    existingEmployee = employeeMapper.selectEmployeeById(employee.getId());
                }

                if (existingEmployee == null) {
                    // 插入新数据
                    employee.setCreateBy(operName);
                    employeeMapper.insertEmployee(employee);
                    successNum++;
                } else if (updateSupport) {
                    // 更新已有数据
                    employee.setUpdateBy(operName);
                    employeeMapper.updateEmployee(employee);
                    successNum++;
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、员工ID " + employee.getId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、员工 " + employee.getEmpName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    /**
     * 验证员工数据格式
     */
    private boolean validateEmployee(Employee employee) {
        // 验证必填字段
        if (StringUtils.isEmpty(employee.getEmpName()) ||
                StringUtils.isEmpty(employee.getGender()) ||
                StringUtils.isEmpty(employee.getDeptName()) ||
                StringUtils.isEmpty(employee.getPhone()) ||
                StringUtils.isEmpty(employee.getEmail())) {
            return false;
        }

        // 验证性别只能是男或女
        if (!("男".equals(employee.getGender()) || "女".equals(employee.getGender()))) {
            return false;
        }

        // 验证邮箱格式
        if (!isEmail(employee.getEmail())) {
            return false;
        }

        // 验证手机号格式
        if (!isMobile(employee.getPhone())) {
            return false;
        }

        return true;
    }

    /**
     * 验证邮箱格式
     */
    private boolean isEmail(String email) {
        if (StringUtils.isEmpty(email)) {
            return false;
        }
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(emailRegex);
        return pattern.matcher(email).matches();
    }

    /**
     * 验证手机号格式
     */
    private boolean isMobile(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return false;
        }
        String mobileRegex = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(mobileRegex);
        return pattern.matcher(mobile).matches();
    }


}
